package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.ThreadLocalUtils;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ghy
 * @version v1.0
 * create on 2022/11/23 8:52
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 菜品减数量
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R sub(@RequestBody ShoppingCart shoppingCart){
        return shoppingCartService.sub(shoppingCart);
    }


    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R clean(){
        //根据用户ID删除购物车数据
        LambdaQueryWrapper<ShoppingCart> lqw = Wrappers.<ShoppingCart>lambdaQuery()
                .eq(ShoppingCart::getUserId, ThreadLocalUtils.get());
        shoppingCartService.remove(lqw);
        return R.success("清空购物车成功");
    }

    /**
     * 展示购物车
     * @return
     */
    @GetMapping("/list")
    public R list(){
        List<ShoppingCart> list = new ArrayList<>();
        //根据用户ID查询，获取购物车列表数据
        LambdaQueryWrapper<ShoppingCart> lqw = Wrappers.<ShoppingCart>lambdaQuery()
                .eq(ShoppingCart::getUserId, ThreadLocalUtils.get());  //user_id = ?
                //.orderByDesc(ShoppingCart::getCreateTime);   //order by create_time desc
        List<ShoppingCart> carts = shoppingCartService.list(lqw);

        return R.success(carts);
    }


    /**
     * 加入菜品或者套餐到购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart){
        return shoppingCartService.add(shoppingCart);
    }



}
